module.exports = {
	getPoints: getPoints,
	getPointsTxList: getPointsTxList,
	getPointsTxByMonth: getPointsTxByMonth,
	getPointsTotal: getPointsTotal,
	getPointsOneTx: getPointsOneTx
};
var db = require('../common/database/db');
var moment = require('moment');


function getPoints(memberId, cb) {
	db.queryWithParamSingle("select * from memberpoints where id=?", [memberId], cb);
}

function getPointsTxList(memberId, types, startDateTs, endDateTs, cb) {
	var startDate = moment(startDateTs).format("YYYY-MM-DD HH:mm:ss");
	var endDate = moment(endDateTs).format("YYYY-MM-DD HH:mm:ss");
	db.queryWithParam('SELECT * FROM mpoints_tx WHERE memberPoints_id=? and txType in (?) and txTime between ? and ? order by txTime desc',
		[memberId, types, startDate, endDate], function (err, txList) {
			if (!err) {
				for (var i in txList) {
                    txJson(txList[i])
				}
			}
			cb(err, txList);
		});
}
function txJson(tx) {
    tx.creator = JSON.parse(tx.creator);
    tx.store = JSON.parse(tx.store);
    tx.terminal = JSON.parse(tx.terminal);
}

function getPointsTxByMonth(memberId, types, startDate, endDate, cb) {
	db.queryWithParamSingle('SELECT count(id) as totalPointAmount FROM mpoints_tx WHERE memberPoints_id=? and txType in (?) and txTime between ? and ? order by txTime desc',
		[memberId, types, startDate, endDate], cb);
}

function getPointsTotal(memberId, types, cb) {
	db.queryWithParamSingle('SELECT COUNT(id) as qty,SUM(pointAmount) as pointsTotal FROM mpoints_tx WHERE memberPoints_id=? AND txType IN (?)',
		[memberId, types], cb);
}

function getPointsOneTx(id, cb) {
	db.queryWithParamSingle("select * from mpoints_tx where id=?", [id], function(err, tx) {
         if (!err) {
             txJson(tx);
         }
         cb(err,tx)
     });
}

